import { ForwardRefRenderFunction, useImperativeHandle, useState, memo, forwardRef, useCallback } from 'react'
import { Button, Col, Divider, Empty, Flex, Modal, Row } from 'antd'
import { useImmer } from 'use-immer'
import { HsAdminSpin } from '@hs-admin/base-components'
import { getProjectInfor, getProjectLog } from '@/api/developCenter/project'
import { projectStageType } from '@/utils/type'
import { EMPTYTEXT, hsHandleTableDateTime } from '@hs-admin/utils'
import { handleButtonShow } from '@/utils/tools'
import { getProjectSourceType } from '@hs-admin/api'

interface Props {
  callEdit: (item: any) => void
}
const DetailModal: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref: any) => {
  const { callEdit } = props
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [loading, setloading] = useState(true)
  const [itemInfor, setItemInfor] = useImmer<any>({
    members: []
  })
  const [detailList, setdetailList] = useState<any[]>([])
  const [logList, setlogList] = useState([])

  const showModal = useCallback(
    (item: any) => {
      setloading(true)
      if (item) {
        getProjectInfor({
          id: item.id
        })
          .then((res) => {
            setItemInfor(res)
            setdetailList([
              {
                label: '项目名称',
                value: res.name
              },
              {
                label: '当前阶段',
                value: projectStageType(res.stage)
              },
              {
                label: '预计/合同金额',
                value: `${Number(res.expected_amount / 10000).toFixed(2)}万`
              },
              {
                label: '来源类型',
                value: getProjectSourceType(res.kind)
              },
              {
                label: '项目负责人',
                value: res.owner_user?.name
              },
              {
                label: '项目团队成员',
                value: res.members.map((ele: { name: string }) => ele.name).join('，')
              }
            ])
          })
          .finally(() => {
            setloading(false)
          })
        getProjectLog({
          id: item.id
        }).then((res) => {
          setlogList(res)
        })
      }
      setIsModalOpen(true)
    },
    [setItemInfor]
  )

  const handleCancel = () => {
    setItemInfor({
      members: []
    })
    setdetailList([])
    setlogList([])
    setIsModalOpen(false)
  }

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal
      }
    },
    [showModal]
  )

  return (
    <Modal title="项目详情" open={isModalOpen} footer={null} onCancel={handleCancel} centered width={1000}>
      {loading && <HsAdminSpin />}
      <Flex align="center" justify="space-between">
        <h2 className="font-bold">规则信息</h2>
        {handleButtonShow('project.project.update', [
          itemInfor.creator_user_id,
          itemInfor.owner_user_id,
          ...itemInfor.members.map((ele: { id: string }) => ele.id)
        ]) && (
          <Button
            type="primary"
            size="large"
            onClick={() => {
              callEdit(itemInfor)
              handleCancel()
            }}>
            编辑
          </Button>
        )}
      </Flex>
      <Row gutter={12}>
        {detailList.map((item) => (
          <Col span={12} key={item.label} className="flex">
            <b className="flex-none w-28">{item.label}：</b>
            <span>{item.value}</span>
          </Col>
        ))}
      </Row>
      <Divider />
      <h2 className="mt-4 font-bold">操作记录</h2>
      {logList?.map((item: any, index: number) => (
        <div key={index} className="mb-2">
          {item.action === 'creation' && (
            <Flex gap="middle" className="mt-2">
              <div className="flex-none w-20">{item.operator_user.name}</div>
              <p className="w-22">创建项目</p>
              <span>{hsHandleTableDateTime(item.created_at)}</span>
            </Flex>
          )}
          {item.action === 'stage_change' && (
            <>
              <Flex gap="middle" className="mt-2">
                <div className="flex-none w-20">{item.operator_user.name}</div>
                <p className="w-22">变更项目阶段</p>
                <span>{hsHandleTableDateTime(item.created_at)}</span>
              </Flex>
              <Flex gap="middle" className="mt-2 ml-24">
                <div>变更前：{item.extra.before_stage ? projectStageType(item.extra.before_stage) : EMPTYTEXT}</div>
                <p>变更后：{item.extra.before_stage ? projectStageType(item.extra.after_stage) : EMPTYTEXT}</p>
              </Flex>
            </>
          )}
        </div>
      ))}
      {!logList?.length && <Empty />}
    </Modal>
  )
}

export default memo(forwardRef(DetailModal))
